import { CircularProgress } from "@nextui-org/react";
import ReactDOM from "react-dom/client";

export default function Loading() {
  return (
    <div
      style={{
        position: "fixed",
        left: "50%",
        top: "50%",
        transform: "translate(-50%, -50%)",
        zIndex: 1000,
      }}
    >
      <CircularProgress size="lg" aria-label="visible" />
    </div>
  );
}

let isLoading = false;
export function getLoadingControl() {
  let loadingDiv: any, loadingRoot: any;

  const openLoading = () => {
    if (isLoading) return;
    isLoading = true;

    loadingDiv = document.createElement("div");
    loadingDiv.setAttribute("id", "loading-div");
    loadingRoot = ReactDOM.createRoot(loadingDiv);

    document.body.appendChild(loadingDiv);
    loadingRoot.render(<Loading />);
  };

  const closeLoading = () => {
    loadingRoot?.unmount();
    const loadingDiv = document.getElementById("loading-div");
    loadingDiv && document.body?.removeChild?.(loadingDiv);
  };

  return {
    openLoading,
    closeLoading,
  };
}
